<?php
namespace app\admin\controller;

use app\admin\model\Article as ArticleModel;
use app\admin\model\Category as CategoryModel;
use app\common\controller\AdminBaseController;
use think\Db;

/**
 * 栏目管理
 * Class Category
 * @package app\admin\controller
 */
class CategoryController extends AdminBaseController {

    protected $category_model;
    protected $article_model;

    protected function _initialize() {
        parent::_initialize();
        $this->category_model = new CategoryModel();
        $category_level_list  = $this->category_model->getLevelList();
        $this->assign('category_level_list', $category_level_list);
    }

    /**
     * 栏目管理
     * @return mixed
     */
    public function index() {
        return $this->fetch();
    }

    /**
     * 添加栏目
     * @param string $pid
     * @return mixed
     */
    public function add($pid = '') {
    	if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Category');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->category_model->allowField(true)->save($data)) {
                    $this->success('保存成功');
                } else {
                    $this->error('保存失败');
                }
            }
        }else{
        	return $this->fetch('add', ['pid' => $pid]);
        }
    }

    /**
     * 更新栏目
     * @param $id
     */
    public function update($id) {
        if ($this->request->isPost()) {
            $data            = $this->request->post();
            $validate_result = $this->validate($data, 'Category');
            if ($validate_result !== true) {
                $this->error($validate_result);
            } else {
                if ($this->category_model->allowField(true)->save($data, $id) !== false) {
                    $this->success('更新成功');
                } else {
                    $this->error('更新失败');
                }
            }
        }else{
        	$category = $this->category_model->find($id);
        	return $this->fetch('update', ['category' => $category]);
        }
    }

    /**
     * 删除栏目
     * @param $id
     */
    public function delete($id) {
        $category = CategoryModel::get(['pid' => $id]);
        if (!empty($category)) {
            $this->error('此分类下存在子分类，不可删除');
        }
        if ($this->category_model->destroy($id)) {
            $this->success('删除成功');
        } else {
            $this->error('删除失败');
        }
    }
}
